/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pb138.jprvyd.gui.form;

import cz.muni.fi.pb138.jprvyd.gui.model.Item_TableModel;
import cz.muni.fi.pb138.jprvyd.*;
import cz.muni.fi.pb138.jprvyd.gui.list.ContactList;
import cz.muni.fi.pb138.jprvyd.gui.Main;
import cz.muni.fi.pb138.jprvyd.gui.list.PaymentMethodList;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

/**
 *
 * @author Jan
 */
public class InvoiceForm extends javax.swing.JFrame {

    int rowIndex;
    public Invoice invoice = null;
    private SwingWorker swingWorker;
    ContactManager contactManager;
    PaymentMethodManager paymentMethodManager;
    public PaymentMethod paymentMethod;
    InvoiceManager invoiceManager;
    public Contact contact;
    Main frame;
    private final boolean ADD = true;
    private final boolean EDIT = false;
    private boolean action;

    /**
     * Creates new form InvoiceGui
     */
    public InvoiceForm() {
        this.invoice = new Invoice();
        invoice.setItems(new ArrayList<Item>());
        this.invoice.setItems(new ArrayList<Item>());
        this.rowIndex = -1;
        this.paymentMethodManager = new PaymentMethodManagerImpl();
        this.contactManager = new ContactManagerImpl();
        this.invoiceManager = new InvoiceManagerImpl();
        action = ADD;
        initComponents();
    }

    public InvoiceForm(Main frame) {
        this.frame = frame;
        this.invoice = new Invoice();
        this.invoice.setItems(new ArrayList<Item>());
        this.rowIndex = -1;
        this.paymentMethodManager = new PaymentMethodManagerImpl();
        this.contactManager = new ContactManagerImpl();
        this.invoiceManager = new InvoiceManagerImpl();
        action = ADD;
        initComponents();
        // invoice number is random
        String number = new Integer(new Random().nextInt(50000)).toString();
        labelInvoiceNumberContent.setText(number);
        Calendar calendar = new GregorianCalendar();
        DateFormat dateFormatter = new SimpleDateFormat("dd. MM. yyyy");
        String date = dateFormatter.format(calendar.getTime());
        calendar.set(Calendar.WEEK_OF_YEAR, calendar.get(Calendar.WEEK_OF_YEAR) + 2);
        String endDate = dateFormatter.format(calendar.getTime());
        textFieldDate.setText(date);
        textFieldEndDate.setText(endDate);

    }

    public InvoiceForm(Main frame, Invoice invoice) {
        this.frame = frame;
        this.invoice = invoice;
        contact = invoice.getContact();
        paymentMethod = invoice.getPaymentMethod();
        rowIndex = -1;
        this.paymentMethodManager = new PaymentMethodManagerImpl();
        this.contactManager = new ContactManagerImpl();
        this.invoiceManager = new InvoiceManagerImpl();
        action = EDIT;
        initComponents();
        String firstName = invoice.getContact().getFirstName();
        String surName = invoice.getContact().getSurname();
        DateFormat dateFormatter = new SimpleDateFormat("dd. MM. yyyy");
        String date = dateFormatter.format(invoice.getDate());
        String endDate = dateFormatter.format(invoice.getEndDate());
        this.textFieldContact.setText(firstName + " " + surName);
        this.textFieldDate.setText(date);
        this.textFieldEndDate.setText(endDate);
        this.textFieldPayment.setText(invoice.getPaymentMethod().getName());
        this.textFieldVarSymbol.setText(new Integer(invoice.getVariableSymbol()).toString());
        this.labelInvoiceNumberContent.setText(new Integer(invoice.getNumber()).toString());

    }

    private class editItemSwingWorker extends SwingWorker<Integer, Void> {

        InvoiceForm form;
        String itemName;

        public editItemSwingWorker(InvoiceForm invoiceForm, String itemName) {
            this.form = invoiceForm;
            this.itemName = itemName;
        }

        @Override
        protected Integer doInBackground() throws Exception {
            List<Item> items = invoice.getItems();
            Item item = new Item();
            for (Item it : items) {
                if (it.getName().equals(itemName)) {
                    item = it;
                    break;
                }
            }

            ItemForm itemForm = new ItemForm(form, invoice, item);
            itemForm.setVisible(true);
            return 0;
        }

        @Override
        protected void done() {
            swingWorker = null;
            rowIndex = -1;
            buttonAddItem.setEnabled(true);
            frame.tableInvoices.updateUI();
        }
    }

    private class saveInvoiceSwingWorker extends SwingWorker<Integer, Void> {

        Invoice invoice;
        private final boolean ADD = true;
        private final boolean EDIT = false;
        private boolean action;
        InvoiceManager invoiceManager;

        public saveInvoiceSwingWorker(Invoice invoice, boolean action, InvoiceManager invoiceManager) {
            this.invoice = invoice;
            this.action = action;
            this.invoiceManager = invoiceManager;
        }

        @Override
        protected Integer doInBackground() throws Exception {
            if (action == ADD) {
                invoiceManager.createInvoice(invoice);
                frame.refreshInvoices(invoice, frame.ADD);
            } else if (action == EDIT) {
                invoiceManager.updateInvoice(invoice);
                frame.refreshInvoices(invoice, frame.EDIT);
            }
            return 0;
        }

        @Override
        protected void done() {
            swingWorker = null;
            buttonSave.setEnabled(true);
        }
    }

    private class deleteItemSwingWorker extends SwingWorker<Integer, Void> {

        Invoice invoice;
        String itemName;
        InvoiceManager invoiceManager;

        public deleteItemSwingWorker(Invoice invoice, String itemName, InvoiceManager invoiceManager) {
            this.invoice = invoice;
            this.itemName = itemName;
            this.invoiceManager = invoiceManager;
        }

        @Override
        protected Integer doInBackground() throws Exception {

            List<Item> itemsUnmodifiable = invoice.getItems();
            List<Item> items = new ArrayList<Item>();
            for (Item item : itemsUnmodifiable) {
                if (!item.getName().equals(itemName)) {
                    items.add(item);
                }
            }
            invoice.setItems(items);
            Item_TableModel model = (Item_TableModel) tableItems.getModel();
            model.deleteItem(rowIndex);
            model.fireTableDataChanged();
            return 0;
        }

        @Override
        protected void done() {
            buttonDeleteItem.setEnabled(true);
            swingWorker = null;
            rowIndex = -1;
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tableItems = new javax.swing.JTable();
        labelInvoiceNumberText = new javax.swing.JLabel();
        labelInvoiceNumberContent = new javax.swing.JLabel();
        labelContact = new javax.swing.JLabel();
        labelDate = new javax.swing.JLabel();
        labelEndDate = new javax.swing.JLabel();
        labelVarSymbol = new javax.swing.JLabel();
        labelPaymentMethod = new javax.swing.JLabel();
        textFieldVarSymbol = new javax.swing.JTextField();
        textFieldEndDate = new javax.swing.JTextField();
        textFieldDate = new javax.swing.JTextField();
        buttonBrowseContacts = new javax.swing.JButton();
        buttonBrowsePayment = new javax.swing.JButton();
        buttonSave = new javax.swing.JButton();
        buttonCance = new javax.swing.JButton();
        buttonContactDetails = new javax.swing.JButton();
        textFieldContact = new javax.swing.JTextField();
        textFieldPayment = new javax.swing.JTextField();
        buttonAddItem = new javax.swing.JButton();
        buttonEditItem = new javax.swing.JButton();
        buttonDeleteItem = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("JPrVyd - Managing invoices");

        tableItems.setModel(new cz.muni.fi.pb138.jprvyd.gui.model.Item_TableModel(invoice.getItems()));
        tableItems.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableItemsMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tableItems);

        labelInvoiceNumberText.setText("Invoice number:");

        labelInvoiceNumberContent.setText("#####");

        labelContact.setText("Contact:");

        labelDate.setText("Issue date:");

        labelEndDate.setText("End date:");

        labelVarSymbol.setText("Variable symbol:");

        labelPaymentMethod.setText("Payment method:");

        buttonBrowseContacts.setText("Browse");
        buttonBrowseContacts.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonBrowseContactsActionPerformed(evt);
            }
        });

        buttonBrowsePayment.setText("Browse");
        buttonBrowsePayment.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonBrowsePaymentActionPerformed(evt);
            }
        });

        buttonSave.setText("Save");
        buttonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSaveActionPerformed(evt);
            }
        });

        buttonCance.setText("Cancel");
        buttonCance.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCanceActionPerformed(evt);
            }
        });

        buttonContactDetails.setText("Contact details");
        buttonContactDetails.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonContactDetailsActionPerformed(evt);
            }
        });

        textFieldContact.setEditable(false);

        textFieldPayment.setEditable(false);

        buttonAddItem.setText("Add item");
        buttonAddItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonAddItemActionPerformed(evt);
            }
        });

        buttonEditItem.setText("Edit item");
        buttonEditItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonEditItemActionPerformed(evt);
            }
        });

        buttonDeleteItem.setText("Delete item");
        buttonDeleteItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonDeleteItemActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(labelInvoiceNumberText)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelInvoiceNumberContent, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(labelVarSymbol)
                            .addComponent(labelEndDate)
                            .addComponent(labelDate)
                            .addComponent(labelContact))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(textFieldContact, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(buttonBrowseContacts, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addComponent(textFieldDate, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(textFieldEndDate, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(textFieldVarSymbol, javax.swing.GroupLayout.Alignment.TRAILING)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(labelPaymentMethod)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(textFieldPayment, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonBrowsePayment, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(buttonAddItem, javax.swing.GroupLayout.DEFAULT_SIZE, 89, Short.MAX_VALUE)
                            .addComponent(buttonSave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(38, 38, 38)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(buttonContactDetails)
                            .addComponent(buttonEditItem, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(buttonCance, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(buttonDeleteItem, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelInvoiceNumberContent)
                    .addComponent(labelInvoiceNumberText))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelContact)
                    .addComponent(buttonBrowseContacts)
                    .addComponent(textFieldContact, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelDate)
                    .addComponent(textFieldDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelEndDate)
                    .addComponent(textFieldEndDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(textFieldVarSymbol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelVarSymbol, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(labelPaymentMethod)
                        .addComponent(textFieldPayment, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(buttonBrowsePayment))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonAddItem)
                    .addComponent(buttonEditItem)
                    .addComponent(buttonDeleteItem))
                .addGap(15, 15, 15)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonSave)
                    .addComponent(buttonCance)
                    .addComponent(buttonContactDetails)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonBrowseContactsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonBrowseContactsActionPerformed

        ContactList contactList = new ContactList(this);
        contactList.setVisible(true);
    }//GEN-LAST:event_buttonBrowseContactsActionPerformed

    private void buttonCanceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCanceActionPerformed
        this.dispose();
    }//GEN-LAST:event_buttonCanceActionPerformed

    private void buttonBrowsePaymentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonBrowsePaymentActionPerformed
        PaymentMethodList paymentList = new PaymentMethodList(this);
        paymentList.setVisible(true);
    }//GEN-LAST:event_buttonBrowsePaymentActionPerformed

    private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveActionPerformed

        String dateString = textFieldDate.getText();
        String endDateString = textFieldEndDate.getText();
        String varSymbolString = textFieldVarSymbol.getText();

        if (contact == null) {
            JOptionPane.showMessageDialog(rootPane, "Choose contact");
        } else if (dateString.equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Enter issue date");
        } else if (endDateString.equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Enter due date");
        } else if (paymentMethod == null) {
            JOptionPane.showMessageDialog(rootPane, "Choose a payment method");
        } else {

            boolean ok = true;
            DateFormat dateParser = new SimpleDateFormat("dd. MM. yyyy");
            Date date = null;
            Date endDate = null;
            try {
                date = dateParser.parse(textFieldDate.getText());
            } catch (ParseException ex) {
                JOptionPane.showMessageDialog(rootPane, "Enter a correct issue date (DD. MM. YYYY)");
                ok = false;
            }
            try {
                endDate = dateParser.parse(textFieldEndDate.getText());
            } catch (ParseException ex) {
                JOptionPane.showMessageDialog(rootPane, "Enter a correct due date (DD. MM. YYYY)");
                ok = false;
            }
            int varSymbol = 0;
            if (!varSymbolString.equals("")) {
                try {
                    varSymbol = Integer.parseInt(textFieldVarSymbol.getText());
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(rootPane, "Variable symbol must be a number");
                    ok = false;
                }
            }
            if (invoice.getItems().isEmpty()) {
                JOptionPane.showMessageDialog(rootPane, "Add items");
                ok = false;
            }
            if (ok) {
                buttonSave.setEnabled(false);
                invoice.setDate(date);
                invoice.setEndDate(endDate);
                invoice.setNumber(new Integer(labelInvoiceNumberContent.getText()));
                invoice.setPaymentMethod(paymentMethod);
                invoice.setContact(contact);
                invoice.setVariableSymbol(varSymbol);

                if (swingWorker != null) {
                    throw new IllegalStateException("Operation in progress");
                }
                swingWorker = new saveInvoiceSwingWorker(invoice, action, invoiceManager);
                swingWorker.execute();
                this.dispose();
            }
        }
    }//GEN-LAST:event_buttonSaveActionPerformed

    private void buttonAddItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAddItemActionPerformed
        ItemForm itemForm = new ItemForm(this, invoice);
        itemForm.setVisible(true);
    }//GEN-LAST:event_buttonAddItemActionPerformed

    private void buttonEditItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonEditItemActionPerformed
        rowIndex = tableItems.getSelectedRow();
        if (rowIndex == -1) {
            JOptionPane.showMessageDialog(rootPane, "No item selected");
        } else {
            if (swingWorker != null) {
                throw new IllegalStateException("Operation in progress");
            }
            buttonAddItem.setEnabled(false);
            Item_TableModel model = (Item_TableModel) tableItems.getModel();
            String itemName = (String) model.getValueAt(rowIndex, 0);
            swingWorker = new editItemSwingWorker(this, itemName);
            swingWorker.execute();
        }
    }//GEN-LAST:event_buttonEditItemActionPerformed

    private void buttonDeleteItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDeleteItemActionPerformed
        rowIndex = tableItems.getSelectedRow();
        if (rowIndex == -1) {
            JOptionPane.showMessageDialog(rootPane, "No item selected");
        } else {
            int choice = JOptionPane.showConfirmDialog(rootPane, "Delete item?", null, JOptionPane.YES_NO_OPTION);
            if (choice == 0) {
                if (swingWorker != null) {
                    throw new IllegalStateException("Operation in progress");
                }
                buttonDeleteItem.setEnabled(false);
                Item_TableModel model = (Item_TableModel) tableItems.getModel();
                String itemName = (String) model.getValueAt(rowIndex, 0);
                swingWorker = new deleteItemSwingWorker(invoice, itemName, invoiceManager);
                swingWorker.execute();
            }
        }
    }//GEN-LAST:event_buttonDeleteItemActionPerformed

    private void buttonContactDetailsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonContactDetailsActionPerformed
        if (contact != null) {
            ContactForm form = new ContactForm(contact);
            form.setVisible(true);
        } else {
            JOptionPane.showMessageDialog(rootPane, "No contact yet");
        }
    }//GEN-LAST:event_buttonContactDetailsActionPerformed

    private void tableItemsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableItemsMouseClicked
        if (rowIndex == tableItems.getSelectedRow()) {
            this.buttonEditItemActionPerformed(null);
        } else {
            rowIndex = tableItems.getSelectedRow();
        }
    }//GEN-LAST:event_tableItemsMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(InvoiceForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(InvoiceForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(InvoiceForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(InvoiceForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new InvoiceForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonAddItem;
    private javax.swing.JButton buttonBrowseContacts;
    private javax.swing.JButton buttonBrowsePayment;
    private javax.swing.JButton buttonCance;
    private javax.swing.JButton buttonContactDetails;
    private javax.swing.JButton buttonDeleteItem;
    private javax.swing.JButton buttonEditItem;
    private javax.swing.JButton buttonSave;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel labelContact;
    private javax.swing.JLabel labelDate;
    private javax.swing.JLabel labelEndDate;
    private javax.swing.JLabel labelInvoiceNumberContent;
    private javax.swing.JLabel labelInvoiceNumberText;
    private javax.swing.JLabel labelPaymentMethod;
    private javax.swing.JLabel labelVarSymbol;
    public javax.swing.JTable tableItems;
    public javax.swing.JTextField textFieldContact;
    private javax.swing.JTextField textFieldDate;
    private javax.swing.JTextField textFieldEndDate;
    public javax.swing.JTextField textFieldPayment;
    private javax.swing.JTextField textFieldVarSymbol;
    // End of variables declaration//GEN-END:variables
}
